package com.hkfn.rfb.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

import androidx.annotation.Nullable;

import com.hkfn.rfb.common.bean.ConstData;
import com.hkfn.rfb.common.utils.TimeUtils;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class SaveDataService extends Service {

    private Timer timer;
    private TimerTask timerTask;

    private int updateViewDataCount = 0;// 5s


    //给客户端使用的binder
    private final IBinder iBinder =  new SaveDataServiceBinder();
    /**
     * 用于客户端绑定器的类。因为我们知道这个服务总是运行在与其客户机相同的进程中，
     * 所以我们不需要处理IPC。
     */
    public class SaveDataServiceBinder extends Binder {
        public SaveDataService getService(){
            //返回MyBinderService实例，以便客户端可以调用公共方法
            return SaveDataService.this;
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        initTimerTask();
        return iBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    private void initTimerTask(){
        if (null != timer) {
            timer.cancel();
            timer = null;
            timerTask = null;
        }
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                // 5s一周期
                if (++updateViewDataCount > 5){
                    updateViewDataCount = 0;
                    // 实时显示时间
                    String formatDateTime = TimeUtils.getFormatDateTime(new Date(), ConstData.TIME_FORMAT_YYYY_MM_DD);
                    saveDataTimerListener.updateViewDataOnTimer(formatDateTime);
                }
            }
        };
        timer.schedule(timerTask, 5000, 1000);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != timer){
            timer.cancel();
            timer = null;
        }
        if (null != timerTask){
            timerTask.cancel();
            timerTask = null;
        }
    }


    /**
     * 保存数据的回调接口
     */
    private SaveDataTimerListener saveDataTimerListener;

    /**
     * 注册回调接口的方法，供外部调用
     * @param saveDataTimerListener
     */
    public void setSaveDataTimerListener(SaveDataTimerListener saveDataTimerListener) {
        this.saveDataTimerListener = saveDataTimerListener;
    }
}
